// 云函数 - 设置支付密码
const cloud = require('wx-server-sdk')
const crypto = require('crypto')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { password } = event

  try {
    // 验证用户登录状态
    if (!wxContext.OPENID) {
      return {
        success: false,
        message: '用户未登录'
      }
    }

    // 验证密码格式
    if (!password || !/^\d{6}$/.test(password)) {
      return {
        success: false,
        message: '请输入6位数字密码'
      }
    }

    // 加密密码
    const hashedPassword = crypto.createHash('sha256').update(password).digest('hex')

    // 查找用户
    const userResult = await db.collection('users').where({
      _openid: wxContext.OPENID
    }).get()

    if (userResult.data.length === 0) {
      // 用户不存在，创建用户记录
      await db.collection('users').add({
        data: {
          _openid: wxContext.OPENID,
          paymentPassword: hashedPassword,
          passwordErrorCount: 0,
          balance: 0,
          totalConsumption: 0,
          createTime: new Date(),
          updateTime: new Date()
        }
      })
    } else {
      // 用户存在，更新支付密码
      await db.collection('users').doc(userResult.data[0]._id).update({
        data: {
          paymentPassword: hashedPassword,
          passwordErrorCount: 0,
          lastPasswordErrorTime: null,
          updateTime: new Date()
        }
      })
    }

    return {
      success: true,
      message: '支付密码设置成功'
    }

  } catch (error) {
    console.error('设置支付密码失败:', error)
    return {
      success: false,
      message: '设置失败，请重试'
    }
  }
}